package com.designpatterns.servicelocatorpattern;

import java.util.ArrayList;
import java.util.List;

public class Cache
{
	private List<Service> services;

	public Cache()
	{
		services = new ArrayList<Service>();
	}

	public Service getService(String serviceName)
	{
		for (Service service : services)
		{
			if (service.getName().equalsIgnoreCase(serviceName))
			{
				System.out.println("Returning cached  " + serviceName + " object");
				return service;
			}
		}
		return null;
	}

	// for循环遍历list，效率有点低，可以考虑java8的流操作
	public void addService(Service newService)
	{
		boolean exists = false;
		for (Service service : services)
		{
			if (service.getName().equalsIgnoreCase(newService.getName()))
			{
				exists = true;
			}
		}
		if (!exists)
		{
			services.add(newService);
		}
	}
}
